<template>
  <MenuPage 
      :columns="examinationCol"
      :data="examList"
      :page.sync="examination.page"
      :size.sync="examination.rows"
      :total="examinationListTotal" 
      :loading="tableLoading"
      @queryFun="queryExaminationList">
    <template slot="search">

<!--        <Divider type="vertical" />-->
        <Checkbox v-model="createByMe" v-if="!this.$route.path.includes('examself')" @on-change="changePage(1)">由我创建</Checkbox>
        <Select filterable
          clearable
          v-if="!this.$route.path.includes('examself')"
          v-model="examination.isQuestion"
          placeholder="是否需要人工阅卷"
          style="width:150px;margin-left: 15px;"
          @on-change="changePage(1)"
        >
          <Option :value="0">否</Option>
          <Option :value="1">是</Option>
        </Select>
<!--        <Select filterable-->
<!--          clearable-->
<!--          v-model="examType"-->
<!--          placeholder="考试类型"-->
<!--          style="width:150px;margin-left: 15px;"-->
<!--          @on-change="changePage(1)"-->
<!--        >-->
<!--          <Option value="0">考试</Option>-->
<!--          <Option value="1">自测</Option>-->
<!--        </Select>-->
        <Select filterable
          clearable
          v-if="!this.$route.path.includes('examself')"
          placeholder="考试状态"
          style="width: 150px;margin-left: 15px "
          v-model="examination.status"
          @on-change="changePage(1)"
        >
          <Option value="0">未开始</Option>
          <Option value="2">进行中</Option>
          <Option value="3">成绩未发布</Option>
          <Option value="1">成绩已发布</Option>
        </Select>
        <Select filterable
          clearable
          v-if="!this.$route.path.includes('examself')"
          v-model="examination.shareStatus"
          style="width: 150px;margin-left: 15px"
          placeholder="可见范围"
          @on-change="changePage(1)"
        >
          <Option :value="0">单位</Option>
          <Option :value="1">个人</Option>
        </Select>
        <Input
          v-model.trim="examination.examinationName"
          placeholder="考试名称"
          style="width: 180px;margin-left: 15px "
          clearable
          @on-change="changePage(1)"
        />

        <Button type="primary" ghost @click="createExam($event, 'add')" class="md-add-jh"
                v-if="!this.$route.path.includes('examself')"
        ><i class="el-icon-edit"></i>创建</Button
        >
      
        <Button
          class="header-btn"
          type="primary"
          ghost
          style="height: 32px;margin-left: 5px;"
          @click="refreshExam()"
          ><i class="el-icon-refresh-right"
        /></Button>
    </template>


    <Modal
        v-model="showTeamPerson"
        title="实验组考试人员"
        :loading="createExamModal.loading"
        :mask-closable="false"
        footer-hide
        width="800px"
    >
      <Form
          ref="examinationformValidate"
          :model="examinationformValidate"
          :rules="ruleexaminationQuestionValidate"
          :label-width="120"
      >
        <FormItem
            label="考试人员"
            prop="classList"
            key="classList"
            v-show="examinationformValidate.classId.length > 0"
        >
          <Card
              dis-hover
              v-for="group in examinationformValidate.classList"
              :key="group.id"
              class="mb10 card-small flex class-card"
          >
            <template slot="title">
              <!-- <small style="font-size: 12px;">实验组： </small> -->
              <Checkbox
                  style="margin-right: 0"
                  :value="group.checkAll"
                  @click.prevent.native="handleCheckAll(group)"
                  disabled
              >
                <Tooltip
                    :content="group.name"
                    placement="top"
                    style="vertical-align: middle"
                >
                <span class="text-ellipsis" style="width: 70px">{{
                    group.name
                  }}</span>
                </Tooltip></Checkbox
              >
            </template>
            <CheckboxGroup
                disabled
                v-model="group.userIds"
                @on-change="handleGroupChange($event, group)"
            >
              <!-- <small style="font-size: 12px;">成员：</small> -->
              <Checkbox
                  :label="user.id"
                  v-for="user in group.userList"
                  :key="user.id"
                  disabled
              >{{ user.nickname }}</Checkbox
              >
            </CheckboxGroup>
            <!--</div>-->
          </Card>
        </FormItem>
      </Form>
    </Modal>
    
    <Modal
      v-model="createExamModal.show"
      :title="createExamModal.title"
      :loading="createExamModal.loading"
      :mask-closable="false"
      @on-ok="saveOprateQuestion('examinationformValidate')"
      @on-cancel="resetField('examinationformValidate')"
      width="800px"
    >
      <Form
        ref="examinationformValidate"
        :model="examinationformValidate"
        :rules="ruleexaminationQuestionValidate"
        :label-width="120"
      >
        <FormItem label="名称" prop="examinationName">
          <Input
            v-model.trim="examinationformValidate.examinationName"
            placeholder='名称不能包含下列任意英文字符 \ / : * ? " < > |，名称长度为1-128个字符'
          ></Input>
        </FormItem>
        <FormItem label="可见范围" prop="shareStatus" key="shareStatus">
          <RadioGroup v-model="examinationformValidate.shareStatus">
            <Radio :label="0">单位</Radio>
            <Radio :label="1">个人</Radio>
          </RadioGroup>
        </FormItem>
        <!-- <FormItem label="选择实验组" prop="classId">
          <Select filterable
            v-model="examinationformValidate.classId"
            placeholder="选择实验组"
            filterable
            @on-change="getCurClass"
          >
            <Option
              v-for="item in classList"
              :key="item.id"
              :value="item.id + '@' + item.className"
              :title="item.className"
              >{{ item.className }}</Option
            >
          </Select>
        </FormItem> -->
        <FormItem label="考试时间" prop="Dates">
          <DatePicker
            :editable="false"
            type="datetimerange"
            v-model="examinationformValidate.Dates"
            format="yyyy-MM-dd HH:mm"
            placement="bottom-end"
            placeholder="选择日期"
            :options="disabledOptions"
            @on-change="startTimeChange"
            style="width: 280px"
          ></DatePicker>
          <span style="color:red;font-size:10px">选择同一天的时间段，请先双击要选择的日期</span>
        </FormItem>
        <!--
        <FormItem label="考试图片" prop="logo">
          <section>
            <Row>
              <Col span="5">
                <Upload ref="upload" :action="uploadAction" :show-upload-list="false" :format="['jpg','jpeg','png']"
                        :on-format-error="handleFormatError" :on-success="getImageUrl" :before-upload="handleBeforeUpload"
                        :headers="uploadHeader">
                  <Button icon="ios-cloud-upload-outline">上传图片</Button>
                  <small v-if="showTip" style="color:red;">请上传jpg,jpeg,png格式图片</small>
                  <img :src="iconSrc" alt="" style="height: 40px;width:auto;display: inline-block; vertical-align: middle;margin-left: 20px;"/>
                </Upload>
                <div class="ivu-form-item-error-tip" v-if="uploaderror">请上传图片</div>
              </Col>
              <Col span="3">
                <img :src="iconSrc" style="width:100%;height:auto" />
              </Col>
            </Row>
          </section>
        </FormItem>
		-->
        <FormItem label="选择试卷" prop="paperId">
          <Select filterable
            v-model="examinationformValidate.paperId"
            placeholder="请选择试卷"
            filterable
            @on-change="getCurPaper"
            class="paper-list"
          >
            <Option
              v-for="item in paperList"
              :key="item.paperId"
              :value="item.paperId + '@' + item.paperName + '@' + item.totalScore"
              :label="item.paperName"
              :title="item.paperName"
            >
              <span class="paper-name">{{ item.paperName }}</span>
              <span style="float:right;color:#ccc">{{
                item.advanced ? '进阶考试' : '普通考试'
              }}</span>
            </Option>
          </Select>
        </FormItem>
         <FormItem label="选择实验组" prop="classId">
           <Select filterable
               v-model="examinationformValidate.classId"
               placeholder="请选择实验组"
               filterable
               multiple
               @on-change="getCurClass"
           >
               <Option
                   v-for="item in classList"
                   :key="item.id"
                   :value="item.id"
                   :title="item.name"
                   >{{ item.name }}</Option
               >
          </Select>
        </FormItem>
        <FormItem
          label="考试人员"
          prop="classList"
          key="classList"
          v-show="examinationformValidate.classId.length > 0"
        >
          <Card
            dis-hover
            v-for="group in examinationformValidate.classList"
            :key="group.id"
            class="mb10 card-small flex class-card"
          >
          <template slot="title">
            <!-- <small style="font-size: 12px;">实验组： </small> -->
            <Checkbox
              style="margin-right: 0"
              :value="group.checkAll"
              @click.prevent.native="handleCheckAll(group)"
              :disabled="group.disabled"
            >
              <Tooltip
                :content="group.name"
                placement="top"
                style="vertical-align: middle"
              >
                <span class="text-ellipsis" style="margin-left:4px;width: 70px">{{
                  group.name
                }}</span>
              </Tooltip></Checkbox
            >
          </template>
          <CheckboxGroup
            v-model="group.userIds"
            @on-change="handleGroupChange($event, group)"
          >
            <!-- <small style="font-size: 12px;">成员：</small> -->
            <Checkbox
              :label="user.id"
              v-for="user in group.userList"
              :key="user.id"
              :disabled="disUserSelect(user, group) || group.disabled"
              >{{ user.nickname }}</Checkbox
            >
          </CheckboxGroup>
          <!--</div>-->
        </Card>
      </FormItem>
        <!-- <FormItem label="考试人员" prop="users" v-if="expGroupUsersList.length">
          <div style="border-bottom: 1px solid #e9e9e9;padding-bottom:6px;margin-bottom:6px;">
            <Checkbox
              :indeterminate="indeterminate"
              :value="checkAll"
              @click.prevent.native="handleCheckAll"
              >全选</Checkbox
            >
          </div>
          <CheckboxGroup v-model="examinationformValidate.users" @on-change="checkAllGroupChange">
            <Checkbox v-for="item in expGroupUsersList" :key="item.userId" :label="item.userId">{{
              item.userName || '-'
            }}</Checkbox>
          </CheckboxGroup>
        </FormItem> -->
        <FormItem label="考试规则" prop="rule">
          <Input
            v-model.trim="examinationformValidate.rule"
            type="textarea"
            :maxlength="200"
            :autosize="{ minRows: 2, maxRows: 5 }"
            placeholder="请输入考试规则"
          ></Input>
        </FormItem>
      </Form>
    </Modal>
    <DrawerPage
        width="1000"
        v-model="rankModal.show"
        :title="`${isGrader ? '评分' : '考试排行'}-${curExamName}`"
        :columns="isGrader ? graderCol : !curExam.classId ? selfRankCol : rankCol"
        :data="rankList"
        :total="rankTotalCount"
        :page.sync="queryRankInfo.page"
        :size.sync="queryRankInfo.rows"
        @change-page="changeRankPage"
        @change-size="changeRankSize"
    >
      <template slot="search">
        <Select filterable
            v-if="isGrader"
            v-model="queryRankInfo.checkStatus"
            placeholder="是否已评分"
            clearable
            style="width: 150px; margin-right: 15px;"
            @on-change="changeRankPage(1)"
          >
            <Option :value="1">是</Option>
            <Option :value="0">否</Option>
          </Select>
          <Input
            v-model.trim="queryRankInfo.userName"
            placeholder="用户名"
            class="radius-input"
            style="width: 180px;"
            clearable
            @on-change="changeName"
          />
      </template>
    </DrawerPage>
    <Modal v-model="showExamDetail" width="1000" footer-hide class-name="vertical-center-modal">
      <exam-detail
        ref="examDetail"
        v-if="showExamDetail"
        :isGrader="isGrader"
        :userScore="scores"
        :examInfo="curExam"
        :isScrollTop="isScrollTop"
        :currentUserName="currentUserName"
        @on-marking="getUserAnswerList"
        :isRemark="isRemark"
        :disabledRemark="disabledRemark"
        @changeRemark="getExamRank"
      ></exam-detail>
    </Modal>
    <Modal
      v-model="showViolationDetail"
      title="违规记录"
      width="800"
      footer-hide
      @on-visible-change="violationPageIndex = 1"
    >
      <TableList 
        :columns="violationCol" 
        :data="violationList"
        :total="violationTotal"
        :page="violationPageIndex"
        :size="violationPageSize"
        @queryFun="getViolationRecord"
      ></TableList>
    </Modal>
    <Modal v-model="getSubmitFlag" :title="getSubmitTitle" width="800" footer-hide>
      <TableList
        :columns="getSubmitRankCol" 
        :data="getSubmitRankData"
        :total="getSubmitRankTotal"
        :page="getSubmitRankPage.page"
        :size="getSubmitRankPage.rows"
        @queryFun="getSubmitRank"
      >
      </TableList>
    </Modal>
    <exam-info ref="testpaper" />
  </MenuPage>
</template>
<script>
import encryption from '@/libs/encryption.js';
import { getDictInfoByName } from '@/api/dict.js';
import { debounce } from '@/libs/utils';
import { mapActions, mapGetters } from 'vuex';
//接口
import {
  queryExam,
  createExam,
  delExam,
  queryExamDetail,
  savePaper,
  getExamRank,
  getPaperDetail,
  delViolationRecord,
  getViolationRecord,
  getUserAnswerList,
  updateExam,
  getSubmitRank,
  getSubmitRankAll,
  startOrFinish,
  submitPaper
} from '@/api/exam';
import { quickCreateContest, reQuickCreateContent } from '@/api/drill_compete';
import { queryClassList } from '@/api/selfStudy/class.js';
import { queryTestPaperList, queryTestPaperQuestionList } from '@/api/testpaper';
import { queryExperGroups, getExperGroupsUsers } from '@/api/users';
import {getGroupHasUsers} from '@/api/company.js'
//组件
import ExamInfo from './examInfo';
import examDetail from './testedInfo';
import pageTitle from '@/mixin/pageTitle';
import { validateName128 } from '@/libs/reg';
import{
  deployStatusMixin
} from '@/mixin/study';
export default {
  mixins: [pageTitle,deployStatusMixin],
  watch: {
    $route(to, from) {
      this.examType = this.$route.name.includes('examself')?'1':'0'
      this.changePage(1)
    },
    showExamDetail(value) {
      // 做这个操作是为了让子组件里的评分输入框同步隐藏
      if (!value) {
        document.body.click();
      } else {
        this.isScrollTop = new Date().getTime();
      }
    }
  },
  data() {
    const validateName = (rule, value, callback) => {
      //验证只能填入数字
      var reg = new RegExp('^[\u4E00-\u9FA5a-zA-Z0-9_ -]*$');
      //验证警戒值
      if (value) {
        // if (!reg.test(value)) {
        //   callback(new Error('请输入中文、数字、字母、下划线、-'));
        // } else {
        //   callback();
        // }
        validateName128(rule, value, callback,128)
      } else {
        callback();
      }
    };
    const validateDate = (rule, value, callback) => {
      //验证只能填入数字
      //var reg = new RegExp("^([1-9]|[1-9]\\d|100)$");
      //验证警戒值
      if (value) {
        if (!this.startDates || !this.endDates) {
          callback(new Error('请选择时间'));
        } else if (new Date(this.startDates).getTime() < new Date().getTime()) {
          callback(new Error('开始时间必须大于当前时间'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    const validateGroupUserNum = (rule, value, callback) => {
        //验证警戒值
        let _this = this;
        if (_this.examinationformValidate.classList.length > 0) {
            if (_this.examinationformValidate.classList.some((group) => group.userIds.length == 0)) {
                callback(new Error('每个班级请至少选择一个成员'));
            } else {
                callback();
            }
        } else {
            callback();
        }
    };
    let September = sessionStorage.getItem('November');
    September = JSON.parse(encryption.SelfUseDecrypt(September));
    return {
      disabledRemark: false,
      isRemark: false,
      isScrollTop: 0,
      showViolationDetail: false,
      violationCol: [
        {
          title: '违规者',
          key: 'creatorName',
          tooltip: true
        },
        {
          title: '违规时间',
          key: 'createTime',
          tooltip: true
        },
        {
          title: '违规类型',
          key: 'type',
          render: (h, params) => {
            return h(
              'Tooltip',
              {
                props: {
                  placement: 'top-start',
                  transfer: true,
                  maxWidth: 200,
                  content: '切屏操作'
                }
              },
              [h('span', {}, '切屏操作')]
            );
          }
        },
        {
          title: '操作',
          key:'action',
          render: (h, params) => {
            return h('div', [
              h(
                'Poptip',
                {
                  props: {
                    confirm: true,
                    'ok-text': '确定',
                    'cancel-text': '取消',
                    type: 'error',
                    size: 'large',
                    title: '你确定要删除吗?',
                    transfer: true
                  },
                  style: {
                    marginLeft: '0px'
                  },
                  on: {
                    'on-ok': () => {
                      this.delViolationRecord(params.row.id);
                    }
                  }
                },
                [
                  h(
                    'Button',
                    {
                      props: {
                        type: 'error',
                        size: 'small'
                      }
                    },
                    [
                      h('Icon', {
                        props: {
                          type: 'md-trash'
                        }
                      })
                    ]
                  )
                ]
              )
            ]);
          }
        }
      ],
      violationList: [],
      violationTotal: 0,
      violationPageIndex: 1,
      violationPageSize: 10,
      examType: this.$route.name.includes('examself')?'1':'0',
      USER_ID: September.userId,
      USER_Name: September.nickname,
      isRootDesigner: September.isRootDesigner,
      examination: {
        status: '',
        examinationName: '',
        page: 1,
        rows: 10,
        createUserId: '',
        isQuestion: '',
        shareStatus: ''
      },
      showTeamPerson:false,
      createExamModal: {
        show: false,
        title: '创建考试',
        type: 1,
        loading: true
      },
      examinationListTotal: 0,
      // examinationCol: this.getColumn(),
      examinationformValidate: {
        examinationName: '',
        classId: [],
        classList: [],
        Dates: [],
        logo: '',
        paperId: '',
        //status:0,
        users: [],
        shareStatus: 0,
        rule: ''
      },
      ruleexaminationQuestionValidate: {
        shareStatus: [
          {
            required: true,
            message: '请选择可见范围',
            type: 'number',
            trigger: 'change'
          }
        ],
        rule: [
          {
            required: true,
            message: '请输入考试规则',
            trigger: 'change'
          }
        ],
        examinationName: [
          {
            required: true,
            max: 128,
            message: '考试名称长度为1-128个字符',
            trigger: 'change'
          },
          {
            validator: validateName,
            trigger: 'change'
          }
        ],
        classId: [
          {
            required: true,
            message: '请选择实验组',
            type: 'array',
            min:1,
            trigger: 'change'
          }
        ],
        classList: [
          {
              required: true,
              type: 'array',
              min: 1,
              validator: validateGroupUserNum,
              trigger: 'change'
          }
        ],
        Dates: [
          {
            required: true,
            type: 'array',
            trigger: 'change',
            message: '请选择时间',
            len: 2
            //          fields: {
            //            0: {
            //              required: true,
            //              message: '请选择开始时间',
            //              trigger: 'change',
            //              type: 'date'
            //            },
            //            1: {
            //              required: true,
            //              message: '请选择结束时间',
            //              trigger: 'change',
            //              type: 'date'
            //            }
            //          }
          },
          {
            validator: validateDate,
            trigger: 'change'
          }
        ],
        paperId: [
          {
            required: true,
            message: '请选择试卷',
            trigger: 'change'
          }
        ],
        // status:[
        //   { required: true, type:'number',message: '请选择状态', trigger: 'change' },
        // ],
        users: [
          {
            required: true,
            type: 'array',
            message: '请选择人员',
            trigger: 'change'
          }
        ]
      },
      initExam: {
        classId: [],
        className: '',
        createTime: '',
        createUser: September.nickname,
        createUserId: September.userId,
        endTime: '',
        examinationName: '',
        id: '',
        logo: '',
        paperId: '',
        startTime: '',
        status: 0,
        classList:[]
      },
      classList: [],
      Dates: [],
      startDates: '',
      endDates: '',
      paperList: [],
      showTip: false,
      uploadAction: '/api/nsrep-ftp/edu-ftp/upload/' + September.userId,
      uploadHeader: {
        Authorization: localStorage.token,
        Accept: '*/*'
      },
      //iconSrc: '',
      uploaderror: false,
      indeterminate: true,
      checkAll: false,
      egid: '',
      expGroupUsersList: [],
      examList: [],
      tableLoading :true,
      testStatus: false,
      serverInter: 0,
      queryRankInfo: {
        page: 1,
        rows: 10,
        userName: '',
        checkStatus: ''
      },
      curExam: {},
      curExamId: '',
      curExamName: '',
      rankList: [],
      rankTotalCount: 0,
      isGrader: false,
      rankModal: {
        show: false
      },
      graderCol: [
        {
          title: '用户名',
          key: 'userName'
        },
        {
          title: '已评分',
          key: 'checkStatus',
          render: (h, params) => {
            let flag = params.row.checkStatus === 0;
            return h(
              'span',
              {
                style: {
                  color: flag ? '#ff9900' : '#19be6b'
                }
              },
              flag ? '否' : '是'
            );
          }
        },
        {
          title: '操作',
          key:'action',
          render: (h, params) => {
            return h(
              'Button',
              {
                props: {
                  icon: 'ios-brush',
                  type: 'text',
                  size: 'small'
                },
                style: {
                  background: 'none',
                  border: 'none',
                  boxShadow: 'none',
                  color: '#2f70ff',
                  disabled: params.row.checkStatus !== 0
                },
                on: {
                  click: () => {
                    this.currentUserName = params.row.userName;
                    this.currentUserId = params.row.userId;
                    this.showExamDetail = true;
                    this.$nextTick(() => {
                      this.$refs.examDetail.getUserAnswer(
                        this.currentPaperId,
                        this.currentUserId,
                        this.curExamId
                      );
                      this.$refs.examDetail.getRankList(this.curExamId, this.currentUserId);
                    });
                  }
                }
              },
              '评分'
            );
          }
        }
      ],
      selfRankCol: [
        {
          title: '用户名',
          key: 'userName',
          width: 120,
          ellipsis: true,
          tooltip: true
        },
        {
          title: '分数',
          key: 'grade'
        },
        {
          title: '是否已点评',
          key: 'remark',
          render: (h, params) => {
            return h('div', [
              h(
                'Poptip',
                {
                  props: {
                    trigger: 'hover',
                    transfer: true,
                    width: 400,
                    disabled: !params.row.remark
                  }
                },
                [
                  h('div', {
                    slot: 'content',
                    domProps: {
                      innerHTML: params.row.remark
                    }
                  }),
                  h(
                    'Tag',
                    {
                      props: {
                        color: !params.row.remark ? 'var(--status-yes)' : 'var(--status-no)'
                      }
                    },
                    params.row.remark ? '是' : '否'
                  )
                ]
              )
            ]);
          }
        },
        {
          title: '操作',
          key:'action',
          width:140,
          opList:[
            {
              txt:"违规记录",
              on: {
                click: (data) => {
                  this.showViolationDetail = true;
                  this.currentUserId = data.userId;
                  this.getViolationRecord();
                }
              }
            },
            {
              txt:'答题详情',
              on: {
                click: (data) => {
                  this.currentUserName = data.userName;
                  this.currentUserId = data.userId;
                  this.showExamDetail = true;
                  this.$nextTick(() => {
                    this.$refs.examDetail.getUserAnswer(
                      this.currentPaperId,
                      this.currentUserId,
                      this.curExamId
                    );
                    this.$refs.examDetail.getRankList(this.curExamId, this.currentUserId);
                  });
                }
              }
            }
          ]
        }
      ],
      rankCol: [
        {
          title: '排名',
          key: 'rank',
          width: 80,
          render: (h, params) => {
            let ele;
            if (params.row._index < 3 && this.queryRankInfo.page == 1) {
              ele = h('img', {
                attrs: {
                  src: require(`../../../assets/exam/top${params.row._index + 1}.png`)
                },
                style: {
                  display: 'inline-block',
                  width: '20px'
                }
              });
            } else {
              ele = h(
                'span',
                params.row._index + 1 + (this.queryRankInfo.page - 1) * this.queryRankInfo.rows
              );
            }
            return ele;
          }
        },
        {
          title: '用户名',
          key: 'userName',
          width: 100,
          ellipsis: true,
          tooltip: true
        },
        {
          title: '班级',
          key: 'className',
          width: 100,
          ellipsis: true,
          tooltip: true
        },
        {
          title: '分数',
          key: 'grade',
          width: 80,
          ellipsis: true,
          tooltip: true
        },
        {
          title: '是否交卷',
          key: 'submitStatus',
          width: 100,
          render: (h, params) => {
            return h(
              'span',
              {
                style: {
                  color: params.row.submitStatus == 1 ? '#19be6b' : '#808695'
                }
              },
              params.row.submitStatus == 1 ? '是' : '否'
            );
          }
        },
        {
          title: '是否已点评',
          key: 'remark',
          width: 100,
          render: (h, params) => {
            return h('div', [
              h(
                'Poptip',
                {
                  props: {
                    trigger: 'hover',
                    transfer: true,
                    width: 400,
                    disabled: !params.row.remark
                  }
                },
                [
                  h('div', {
                    slot: 'content',
                    domProps: {
                      innerHTML: params.row.remark
                    }
                  }),
                  h(
                    'Tag',
                    {
                      props: {
                        color: !params.row.remark ? 'var(--status-yes)' : 'var(--status-no)'
                      }
                    },
                    params.row.remark ? '是' : '否'
                  )
                ]
              )
            ]);
          }
        },
        {
          title: '操作',
          key:'action',
          width:140,
          render: (h, params) => {
            return h('div', [
              // 结束考试
              h(
                'Poptip',
                {
                  props: {
                    confirm: true,
                    'ok-text': '确定',
                    'cancel-text': '取消',
                    size: 'large',
                    title: '你确定要结束考试吗?',
                    transfer: true
                  },
                  style: {
                    marginLeft: '0px'
                  },
                  on: {
                    'on-ok': () => {
                      this.submitPaper(params.row.userId);
                    }
                  }
                },
                [
                  h(
                    'Button',
                    {
                      attrs: {
                        title: '结束考试'
                      },
                      props: {
                        type: 'text',
                        size: 'small',
                        disabled: params.row.submitStatus == 1 ? true : false
                      },
                      style: {
                        background: 'none',
                        border: 'none',
                        boxShadow: 'none'
                      }
                    },
                    [
                      h('Icon', {
                        props: {
                          type: 'md-power',
                          size: 19
                        },
                        style: {
                          color: params.row.submitStatus == 1 ? '#c5c8ce' : '#2f70ff'
                        }
                      }),
                      h(
                        'span',
                        {
                          style: {
                            // cursor: 'pointer',
                            color: params.row.submitStatus == 1 ? '#c5c8ce' : '#2f70ff'
                          }
                        },
                        '结束考试'
                      )
                    ]
                  )
                ]
              ),

              h(
                'Button',
                {
                  props: {
                    type: 'text',
                    size: 'small'
                  },
                  style: {
                    background: 'none',
                    border: 'none',
                    boxShadow: 'none'
                  },
                  on: {
                    click: () => {
                      this.showViolationDetail = true;
                      this.currentUserId = params.row.userId;
                      this.getViolationRecord();
                    }
                  }
                },
                [
                  h('img', {
                    attrs: {
                      src: require('../../../assets/globalIcon/check.png')
                    },
                    style: {
                      cursor: 'pointer',
                      'margin-right': '5px',
                      'vertical-align': 'middle',
                      width: '16px',
                      height: '16px',
                      display: 'inline-block'
                    }
                  }),
                  h(
                    'span',
                    {
                      style: {
                        cursor: 'pointer',
                        color: '#2f70ff'
                      }
                    },
                    '违规记录'
                  )
                ]
              ),
              h(
                'Button',
                {
                  props: {
                    type: 'text',
                    size: 'small'
                  },
                  style: {
                    background: 'none',
                    border: 'none',
                    boxShadow: 'none'
                  },
                  on: {
                    click: () => {
                      this.currentUserName = params.row.userName;
                      this.currentUserId = params.row.userId;
                      this.showExamDetail = true;
                      this.$nextTick(() => {
                        this.$refs.examDetail.getUserAnswer(
                          this.currentPaperId,
                          this.currentUserId,
                          this.curExamId
                        );
                        this.$refs.examDetail.getRankList(this.curExamId, this.currentUserId);
                      });
                    }
                  }
                },
                [
                  h('img', {
                    attrs: {
                      src: require('../../../assets/globalIcon/check.png')
                    },
                    style: {
                      cursor: 'pointer',
                      'margin-right': '5px',
                      'vertical-align': 'middle',
                      width: '16px',
                      height: '16px',
                      display: 'inline-block'
                    }
                  }),
                  h(
                    'span',
                    {
                      style: {
                        cursor: 'pointer',
                        color: '#2f70ff'
                      }
                    },
                    '答题详情'
                  )
                ]
              )
            ]);
          }
        }
      ],
      showExamDetail: false,
      currentUserId: '',
      currentUserName: '',
      currentPaperId: '',
      curStatus: 0,
      objective: [],
      ctflist: [],
      paperName: '',
      scores: '',
      objectives: [],
      objectivem: [],
      objectivep: [],
      maxHeight: document.documentElement.clientHeight - 305,
      showDefImg: true,
      showDefText: '加载中',
      createByMe: false,
      disabledOptions: {
        disabledDate(date) {
          return date && date.valueOf() < Date.now() - 86400000;
        }
      },
      questionList: [],
      getSubmitRankPage: {
        page: 1,
        rows: 10,
        userName: ''
      },
      getSubmitRankCol: [
        {
          title: '昵称',
          key: 'userName',
          tooltip: true
        },
        {
          title: '得分',
          key: 'grade',
          tooltip: true
        },
        {
          title: '交卷时间',
          key: 'submitTime',
          tooltip: true
        }
      ],
      getSubmitRankData: [],
      getSubmitFlag: false,
      getSubmitTitle: '',
      getSubmitRankTotal: 0
    };
  },
  components: {
    ExamInfo,
    examDetail
  },
  computed: {
    hasEnv() {
      return this.questionList.some((item) => [1, '1', 'true'].includes(item.needEnv));
    },
    examinationCol(){
      return [
        //      {
        //        type: 'index',
        //        width: 60,
        //        align: 'center',
        //        tooltip: true,
        //      },
        {
          type:"link",
          placement: 'top-left',
          title: '名称',
          key: 'examinationName',
          tooltip: true,
          width: 320,
          minWidth:100,
          disabled:(data) => {
            return data.paperType == 'paper_random'
          },
          on: {
            click: (data) => {
              this.$refs.testpaper.openModal(data.paperId);
            }
          }
          // render: (h, params) => {
          //   let disabled = params.row.paperType == 'paper_random';
          //   return h(
          //     'Tooltip',
          //     {
          //       props: {
          //         maxWidth: 400,
          //         placement: 'top-start',
          //         content: params.row.examinationName
          //       },
          //       attrs: {}
          //     },
          //     [
          //       h(
          //         'div',
          //         {
          //           style: {
          //             color: '#2d8cf0',
          //             cursor: disabled ? 'not-allowed' : 'pointer',
          //             width: '130px'
          //           },
          //           attrs: {
          //             class: 'text-ellipsis'
          //           },
          //           on: {
          //             click: () => {
          //               if (disabled) return;
          //               this.$refs.testpaper.openModal(params.row.paperId);
          //             }
          //           }
          //         },
          //         params.row.examinationName
          //       )
          //     ]
          //   );
          // }
        },
        {
          title: '交卷人数',
          key: 'submitCount',
          placement: 'top-right',
          show:(data,e) => {
            return !this.$route.path.includes('examself')
          },
          width: 60,
          minWidth:100,
          render: (h, params) => {
            return h(
                'Tag',
                {
                  props: {
                    color: 'green'
                  },
                  style: {
                    'text-align-last': 'justify',
                    cursor: 'pointer!important'
                  },
                  nativeOn: {
                    click: () => {
                      this.curExamId = params.row.id;
                      this.getSubmitTitle = `交卷人数 - [ ${params.row.examinationName} ]`;
                      this.getSubmitRank();
                    }
                  }
                },
                params.row.submitCount
            );
          }
        },
        {
          title: '考试类型',
          show:(data,e) => {
            return false
          },
          key: 'classId',
          placement: 'top-right',
          width: 60,
          minWidth:100,
          render: (h, params) => {
            return h(
                'span',
                {
                  style: {
                    color: params.row.type === 1 ? 'red' : 'green'
                  }
                },
                params.row.type === 1 ? '自测' : '考试'
            );
          }
        },
        {
          title: '分数',
          key: 'grade',
          placement: 'top-right',
          width: 60,
          show:(data,e) => {
            return this.$route.path.includes('examself')
          },
          render: (h, params) => {
            let grade = Number(params.row.grade) || 0
            return h(
                'Tag',
                {
                  props: {
                    color: 'green'
                  }
                },
                grade<0?'未发布':grade
            );
          }
        },
        {
          title: '总分',
          key: 'paperScore',
          placement: 'top-right',
          width: 60,
          render: (h, params) => {
            return h(
                'Tag',
                {
                  props: {
                    color: 'green'
                  }
                },
                params.row.paperScore
            );
          }
        },
        {
          title: '考试状态',
          key: 'status',
          placement: 'top-right',
          width: 90,
          minWidth:140,
          show:(data,e) => {
            return !this.$route.path.includes('examself')
          },
          render: (h, params) => {
            let { color, txt } = this.statusQFilter(params.row.status);
            return h(
                'span',
                {
                  style: {
                    color: color,
                    text: txt
                  }
                },
                txt
            );
          }
        },
        {
          title: '工程部署状态',
          key: 'deployStatus',
          align: 'center',
          show:(data,e) => {
            return !this.$route.path.includes('examself')
          },
          width: 100,
          tooltip: true,
          setColor: (deployStatus) => { //混入
            return this.filterDeployStatus(deployStatus, 'color');
          },
          filter: (deployStatus) => {
            return this.filterDeployStatus(deployStatus, 'text');
          }
          // render: (h, params) => {
          //   let { projectId, deployStatus } = params.row;
          //   let obj = this.deployStatusFilter(deployStatus);
          //   if (projectId) {
          //     return h(
          //       'Tag',
          //       {
          //         props: {
          //           type: 'border',
          //           color: obj.color
          //         }
          //       },
          //       obj.text
          //     );
          //   } else {
          //     return h('span', '-');
          //   }
          // }
        },
        {
          title: '人工阅卷',
          key: 'isQuestion',
          placement: 'top-right',
          width: 60,
          minWidth:100,
          show:(data,e) => {
            return !this.$route.path.includes('examself')
          },
          render: (h, params) => {
            return h(
                'Tag',
                {
                  props: {
                    type:'border',
                    color: params.row.isQuestion == 0 ? 'var(--status-no)' : 'var(--status-yes)'
                  }
                },
                params.row.isQuestion == 0 ? '否' : '是'
            );
          }
        },
        {
          // title: '班级名称',
          type:"link",
          title: '实验组',
          key: 'classNameList',
          align: 'center',
          width: 100,
          tooltip: true,
          show:(data,e) => {
            return !this.$route.path.includes('examself')
          },
          filter:(classNameList) => {
            return classNameList ? classNameList.join(',') : ''
          },
          on: {
            click: (data) => {
              this.createExam(data, 'showTeamPerson');
            }
          }
        },
        {
          title: '自测人',
          key: 'createUser',
          show:(data,e) => {return this.$route.path.includes('examself')},
          align: 'center',
          width: 100,
          tooltip: true
        },
        {
          title: '可见范围',
          key: 'shareStatus',
          align: 'center',
          width: 100,
          tooltip: true,
          show:(data,e) => {
            return !this.$route.path.includes('examself')
          },
          render: (h, params) => {
            let isPrivate = params.row.shareStatus == 1;
            return h(
                'span',
                {
                  style: {
                    color: isPrivate ? '#FFA500' : '#32CD32'
                  }
                },
                isPrivate ? '个人' : '单位'
            );
          }
        },
        {
          title: '试卷名称',
          key: 'paperName',
          align: 'center',
          width: 100,
          tooltip: true
        },

        {
          title: '开始时间',
          key: 'startTime',
          align: 'center',
          width: '120',
          // render: (h, params) => {
          //   let time = '-'
          //   if(params.row.startTime)time =  params.row.startTime+' ~ '+params.row.endTime
          //   return h('span', {}, time);
          // }
        },
        {
          title: '结束时间',
          key: 'endTime',
          width: 120,
          align: 'center'
        },
        {
          title: '创建者',
          key: 'createUser',
          show:(data,e) => {return !this.$route.path.includes('examself')},
          align: 'center',
          width: 150,
          tooltip: true
        },
        {
          title: '操作',//自测的操作
          key:'action',
          fold:!this.$route.path.includes('examself'),// 按钮折叠
          foldWidth:'253px',// 展开按钮的背板大小
          width: 150,
          placement: 'top-right',
          slot: 'action',
          // fixed:'right',
          opList: [
            {
              txt: '开始',
              tooltip: true,
              show:(data,e) => {
                return !this.$route.path.includes('examself')
              },
              title: '你确定要开始考试吗?',
              disabled: (data) => {
                return data.createUserId != this.USER_ID || [1, 2, 3].includes(data.status);;
              },
              on:{
                click: (data,e) => {
                  this.startOrFinish(data.id, 2);
                }
              }
            },
            {
              txt: '结束',
              show:(data,e) => {return !this.$route.path.includes('examself')},
              tooltip: true,
              title: '你确定要结束考试吗?',
              disabled: (data) => {
                return data.createUserId != this.USER_ID || [0, 1, 3].includes(data.status);
              },
              on:{
                click: (data,e) => {
                  this.startOrFinish(data.id, 3);
                }
              }
            },
            {
              txt:'再次部署',
              show:(data,e) => {return !this.$route.path.includes('examself')},
              tooltip: true,
              title: '你确定要再次部署吗?',
              disabled: (data) => {
                return this.setReBtnStatus(data) ||
                    ![0, 6, 10].includes(data.deployStatus) ||
                    !data.projectId;
              },
              on:{
                click: (data,e) => {
                  this.reQuickCreateContent(data.id);
                }
              }
            },
            {
              txt: '修改',
              show:(data,e) => {return !this.$route.path.includes('examself')},
              disabled: this.setReBtnStatus,
              on:{
                click: (data,e) => {
                  this.createExam(data, 'modify');
                }
              }
            },
            {
              txt: '报告',
              disabled: (data) => {
                return data.status == 3 || data.status == 0 || data.status == 2;
              },
              on:{
                click: (data,e) => {
                  const { href } = this.$router.resolve({
                    name: 'examReport',
                    query: {
                      id: data.id
                    }
                  });


                  window.openTrain(href, '_blank');
                }
              }
            },
            {
              txt: '评分',
              show:(data,e) => {return !this.$route.path.includes('examself')},
              disabled: (data) => {
                return (
                    data.createUserId != this.USER_ID ||
                    data.status == 0 ||
                    data.status == 1 ||
                    data.status == 2 ||
                    data.isQuestion == 0
                );
                // return data.status == 3 || data.status == 0 || data.status == 2;
              },
              on:{
                click: (data,e) => {
                  this.curExam = data;
                  this.curExamId = data.id;
                  this.curExamName = data.examinationName;
                  this.currentPaperId = data.paperId;
                  this.curStatus = data.status;
                  this.queryRankInfo.userName = '';
                  this.queryRankInfo.page = 1;
                  this.queryRankInfo.checkStatus = '';
                  this.isGrader = true;
                  this.getUserAnswerList();
                }
              }
            },
            {
              txt: '排行',
              show:(data,e) => {return !this.$route.path.includes('examself')},
              disabled: (data) => {
                return data.status == 3 || data.status == 0 || data.status == 2;
              },
              on:{
                click: (data,e) => {
                  this.curExam = data;
                  this.curExamId = data.id;
                  this.curExamName = data.examinationName;
                  this.currentPaperId = data.paperId;
                  this.curStatus = data.status;
                  this.disabledRemark =
                      data.createUserId != this.USER_ID && data.type !== 1;
                  this.queryRankInfo.userName = '';
                  this.queryRankInfo.page = 1;
                  this.isGrader = false;
                  this.getExamRank();
                }
              }
            },
            {
              txt: '发布成绩',
              show:(data,e) => {return !this.$route.path.includes('examself')},
              disabled: (data) => {
                return (
                    data.createUserId != this.USER_ID ||
                    data.status !== 3 ||
                    data.isSendScore === 1
                );
              },
              on:{
                click: (data,e) => {
                  this.publishScore(data)
                }
              }
            },
            {
              txt: '删除',
              type: 'delete',
              tooltip: true,
              title: '你确定要删除吗?',
              disabled: (data) => {
                return data.createUserId != this.USER_ID || data.status == 2;
              },
              on:{
                click: (data,e) => {
                  this.delExam(data.id);
                }
              }
            },
            {
              txt: '进入环境',
              show:(data,e) => {return !this.$route.path.includes('examself')},
              disabled: (data) => {
                return !data.projectId
              },
              on:{
                click: (data,e) => {
                  if(data && data.projectId)
                    window.openTrain(
                        `/jjzzTopo/index.html#/ProjectViews?projectId=${data.projectId}`
                    );
                }
              }
            }
          ]
        }
      ]
    }
  },
  filters: {},
  methods: {
    getOperbtn(data,list,h){
      let btns = []
      
      list.forEach(l=>{
        let disabled = l.disabled
        if(l.disabled instanceof Function){
          disabled = l.disabled(data)
        }
        
        let show = true
        if(l.show){
          show = l.show(data)
        }
        let color =''
        if(!disabled) color='var(--operation-useable)'
        if(l.type=='delete') color='red'
        let btn =  h(
                "span",
                {
                  props: {
                    type: "primary",
                    size: "small"
                  },
                  style:{
                    margin:'10px',
                    color:color,
                    cursor: disabled?'not-allowed':'pointer'
                  },
                  on: {
                    click: () => {
                        if(disabled) return
                        if(l.tooltip){
                          this.$Modal.confirm({
                            title: l.title,
                            onOk: () => {
                              l.on.click(data)
                            }
                          });
                        }else {
                          l.on.click(data)
                        }
                    }
                  }
                },
            (l.txt)
            )

        if(show) btns.push(btn)
      })
      
      return btns
    },
    


    getDictInfoByName() {
      getDictInfoByName({ name: 'remark' }).then(({ code, attribute, message }) => {
        if (code == 1) {
          this.isRemark = attribute.data.value === '1';
        } else {
          if (message === '没查询到数据') {
            // 该数据没有查询到时，并不需要提示错误信息
            this.isRemark = false;
            return;
          }
          this.isRemark = false;
          this.$Message.warning(message);
        }
      });
    },
    // 结束用户考试
    submitPaper(userId) {
      submitPaper(this.curExamId, userId)
        .then((res) => {
          if (res.code == 1) {
            this.$Message.success({
              content: res.message,
              duration: 3
            });
            this.getExamRank();
          } else {
            this.$Message.error(res.message);
          }
        })
        .catch((error) => {
          this.$Message.error({
            content: '操作失败',
            duration: 3
          });
        });
    },
    // 手动开始、结束考试
    startOrFinish(id, status) {
      startOrFinish(id, status).then((res) => {
        if (res.code == 1) {
          this.queryExaminationList();
          this.$Message.success(res.message);
        } else {
          this.$Message.error(res.message);
        }
      });
    },
    // 再次部署
    reQuickCreateContent(id) {
      reQuickCreateContent(id, null, false)
        .then((data) => {
          if (data.code === 1) {
            this.$Message.info('再次部署中...');
            this.queryExaminationList();
          } else {
            this.$Message.warning(data.message);
          }
        })
        .catch((error) => {
          this.$Message.error('再次部署异常');
        });
    },
    deployStatusFilter(deployStatus) {
      switch (String(deployStatus)) {
        case '0':
          return {
            text: '未部署',
            color: '#888'
          };
        case '1':
          return {
            text: '部署中',
            color: '#06b649'
          };
        case '2':
          return {
            text: '待部署',
            color: '#888'
          };
        case '3':
          return {
            text: '部署成功',
            color: '#06b649'
          };
        case '4':
          return {
            text: '删除中',
            color: '#ff4242'
          };
        case '5':
          return {
            text: '已修改',
            color: '#888'
          };
        case '6':
          return {
            text: '部署失败',
            color: '#ff4242'
          };
        case '7':
          return {
            text: '修改错误',
            color: '#fa9901'
          };
        case '8':
          return {
            text: '删除失败',
            color: '#fa9901'
          };
        case '9':
          return {
            text: '部署中',
            color: '#06b649'
          };
        case '10':
          return {
            text: '未绑定工程',
            color: '#888'
          };
        case '11':
          return {
            text: '修改失败',
            color: '#fa9901'
          };
        case '12':
          return {
            text: '待删除',
            color: '#888'
          };
        case '13':
          return {
            text: '清空部署中',
            color: '#ff8244'
          };
        case '14':
          return {
            text: '清空部署失败',
            color: '#ff8244'
          };
        case '15':
          return {
            text: '部署校验中',
            color: '#ff8244'
          };
        case '16':
          return {
            text: '工程导入中',
            color: '#088cf0'
          };
        case '17':
          return {
            text: '工程导入失败',
            color: '#cb0236'
          };
      }
    },
    queryTestPaperQuestionList(id) {
      return new Promise((resolve) => {
        queryTestPaperQuestionList({ paperId: id })
          .then(({ code, message, data = {} }) => {
            if (code !== 1) {
              this.$Message.warning(message);
              this.questionList = [];
              return;
            }
            this.questionList = data.paperQuestion;
          })
          .catch(() => {
            this.$Message.error('查询试卷详情异常');
            this.questionList = [];
          })
          .finally(() => {
            resolve();
          });
      });
    },
    async createTopo(id, name, users) {
      let sceneOptions = {
        contestId: id,
        contestName: name,
        vmInEnable: true,
        partyEnable: false,
        teams: [],
        contestPapers: [],
        type: 'examination',
        pmInEnable: false
      };
      // 将选中的考试人员解析为快速构建时的团队，每个考试人员单独为一个团队
      // let users = this.examinationformValidate.users;
      sceneOptions.teams = users.map(user => {
        return {
          addUserEnable: false,
          id: user.userId,
          name: user.userName
        }
      })
      // this.expGroupUsersList.forEach((item) => {
      //   if (users.includes(item.userId)) {
      //     sceneOptions.teams.push({
      //       addUserEnable: false,
      //       id: item.userId,
      //       name: item.userName
      //     });
      //   }
      // });
      // 将需要环境的题目从试卷中解析出来，用于快速构建
      sceneOptions.contestPapers = this.questionList
        .filter((item) => [1, '1', 'true'].includes(item.needEnv))
        .map((item) => {
          return {
            flavorRef: item.flavorId,
            imageRef: item.imageId,
            name: item.name
          };
        });
      quickCreateContest(sceneOptions)
        .then((data) => {
          if (data.code === 1) {
            // 快速构建成功，将工程信息与考试绑定
            data = data.data || {};
            let { projectId, projectName } = data;
            updateExam({
              id,
              projectId,
              projectName
            })
              .then((data) => {
                // 绑定快速构建场后的工程信息与竞赛、演练的关系
                if (data.code !== 1) {
                  this.$Message.warning(data.message);
                  this.createExamModal.loading = false;
                  setTimeout(function() {
                    this.createExamModal.loading = true;
                  });
                } else {
                  this.hideModal();
                }
              })
              .catch(() => {
                this.createExamModal.loading = false;
                setTimeout(function() {
                  this.createExamModal.loading = true;
                });
                this.$Message.error('修改场景异常');
              });
          } else {
            if (data.message) {
              this.$Message.warning(data.message);
              this.createExamModal.loading = false;
              setTimeout(function() {
                this.createExamModal.loading = true;
              });
            }
          }
        })
        .catch(() => {
          this.createExamModal.loading = false;
          setTimeout(function() {
            this.createExamModal.loading = true;
          });
          this.$Message.error('快速构建异常');
        });
    },
    // 获取违规记录
    getViolationRecord(pageIndex) {
      if (pageIndex) {
        this.violationPageIndex = pageIndex;
      }
      getViolationRecord({
        pageIndex: this.violationPageIndex,
        pageSize: this.violationPageSize,
        type: 0,
        examinationId: this.curExamId,
        creator: this.currentUserId
      })
        .then(({ code, message, data }) => {
          if (code !== 1) {
            this.$Message.warning(message);
          } else {
            this.violationTotal = data.total;
            this.violationList = data.items || [];
          }
        })
        .catch(() => {
          this.$Message.error('获取违规记录异常');
        });
    },
    delViolationRecord(id) {
      delViolationRecord(id)
        .then(({ code, message }) => {
          if (code !== 1) {
            this.$Message.warning(message);
          } else {
            this.$Message.info('删除违规记录成功');
            this.violationPageIndex =
              this.violationPageIndex > 1 && this.violationList.length === 1
                ? this.violationPageIndex - 1
                : this.violationPageIndex;
            this.getViolationRecord();
          }
        })
        .catch(() => {
          this.$Message.error('删除违规记录异常');
        });
    },
    // 设置高度
    setStyle() {
      window.fullHeight = document.documentElement.clientHeight;
      window.fullWidth = document.documentElement.clientWidth;
      this.fullHeight = window.fullHeight;
      this.fullWidth = window.fullWidth;
      this.setTableHei = this.fullHeight - 197;
      this.examination.rows = Math.floor(this.setTableHei / 96) || 1;
      let maxPage = Math.ceil(this.examinationListTotal / this.examination.rows);
      if (maxPage < this.examination.page) {
        this.examination.page = maxPage;
      }
    },
    createExam(obj, type) {
      let _this = this;
      _this.checkAll = false;
      _this.expGroupUsersList = [];
      _this.initFormdata();
      _this.examinationformValidate.Dates = [];
      Promise.all([_this.queryClassList(), _this.queryTestPaperList()])
        .then((data) => {
          if (type === 'add') {
            _this.createExamModal.type = 1;
            _this.createExamModal.title = '创建考试';
            _this.createExamModal.show = true;
            _this.examinationformValidate.Dates = [
              this.timestampToTime(new Date().getTime() + 60 * 3 * 1000),
              this.timestampToTime(new Date().getTime() + 60 * 63 * 1000)
            ];
            _this.startTimeChange(_this.examinationformValidate.Dates);
          } else {
            _this.createExamModal.type = 2;
            _this.createExamModal.title = '修改考试';
            queryExamDetail(obj.id).then((data) => {
              if (data.code === 1) {
                let dataObj = data.attribute.data;
                _this.examinationformValidate = Object.assign(this.examinationformValidate,data.attribute.data);
                // _this.examinationformValidate.classId = `${dataObj.classId}@${dataObj.className}`;
                //  _this.examinationformValidate.classId = dataObj.classId;
                _this.examinationformValidate.paperId = `${dataObj.paperId}@${dataObj.paperName}@${dataObj.paperScore}`;
                _this.examinationformValidate.Dates = [
                  data.attribute.data.startTime,
                  data.attribute.data.endTime
                ];
                _this.startDates = data.attribute.data.startTime;
                _this.endDates = data.attribute.data.endTime;
                // _this.getCurClass(dataObj.classId);
                this.saveUsers = dataObj.users.map(user => {
                  if(!user.classId){
                    return {
                      ...user,
                      classId:this.examinationformValidate.classId,
                      className:this.examinationformValidate.className
                    } 
                  }else{
                    return user
                  }
                })
                if(dataObj.users.some(user => !user.classId)){
                  this.examinationformValidate.classId = [this.examinationformValidate.classId]
                }else{
                  this.examinationformValidate.classId = [...new Set(dataObj.users.map((user) => user.classId))];
                }
                _this.createExamModal.show = true;
                _this.showTeamPerson = false
                
                if(type==='showTeamPerson'){
                  _this.createExamModal.show = false;
                  _this.showTeamPerson = true
                }
                
              } else {
                _this.$Message.error(data.message);
              }
            });
          }
        })
        .catch((error) => {});
    },
    timestampToTime(timestamp) {
      var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + '-';
      var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
      var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
      var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
      var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
      //      var s = date.getSeconds();
      return Y + M + D + h + m;
    },
    initFormdata() {
      this.examinationformValidate = {
        examinationName: '',
        classId: [],
        classList: [],
        sceneTmplDec: '',
        Dates: [],
        logo: '',
        paperId: '',
        //status:0,
        users: [],
        shareStatus: 0,
        rule: ''
      };
    },
    refreshExam() {
      this.examination = {
        status: '',
        examinationName: '',
        page: 1,
        rows: 10,
        createUserId: '',
        isQuestion: '',
        shareStatus: ''
      }
      this.examType = '';
      // this.setStyle();
      this.createByMe = false;
      this.queryExaminationList();
    },
    queryExaminationList: debounce(function(roll) {
      if(!roll){
        this.tableLoading = true
      }
      let _this = this;
      if (this.createByMe) {
        _this.examination.createUserId = this.USER_ID;
      }
      this.examination.examType = this.examType;
      queryExam(_this.examination).then((data) => {
        if (data.code == 1) {
          _this.examination.createUserId = '';
          _this.examList = data.attribute.dataList;
          _this.examinationListTotal = data.attribute.totalCount;
          if (_this.examList.length <= 0) {
            _this.showDefImg = true;
            _this.showDefText = '暂无信息';
          } else {
            _this.showDefImg = false;
          }
        } else {
          _this.showDefImg = true;
          _this.showDefText = '暂无信息';
          _this.$Message.error(data.message);
        }
        this.tableLoading = false
      }).catch(error => {
        this.tableLoading = false
      });
    }, 500),
    changePage(val) {
      this.examination.page = val;
      this.showDefImg = true;
      this.showDefText = '加载中';
      this.queryExaminationList();
    },
    saveOprateQuestion(name) {
      let _this = this;
      _this.$refs[name].validate((valid) => {
        if (valid) {
          let obj = {};
          Object.assign(obj, _this.initExam, _this.examinationformValidate);
          obj.startTime = _this.startDates;
          obj.endTime = _this.endDates;
          // obj.classId = _this.examinationformValidate.classId.split('@')[0];
          // obj.className = _this.examinationformValidate.classId.split('@')[1];
          // obj.classId = _this.examinationformValidate.classId;
          // obj.className = _this.classList.find((item) => item.id === obj.classId).name;
          obj.paperId = _this.examinationformValidate.paperId.split('@')[0];
          obj.paperName = _this.examinationformValidate.paperId.split('@')[1];
          obj.paperScore = _this.examinationformValidate.paperId.split('@')[2];
          obj.users = []
          let userIds = [];
          _this.examinationformValidate.classList.forEach((group) => {
              group.userList.forEach((user) => {
                  if (
                      !userIds.includes(user.id) &&
                      group.userIds.includes(user.id)
                  ) {
                      obj.users.push({
                          classId: group.id,
                          className: group.name,
                          userId: user.id,
                          userName: user.nickname
                      });
                      userIds.push(user.id);
                  }
              });
          });
          obj.classId = '-';
          obj.className = '-';
          delete obj.classList;
          delete obj.Dates;
          if (_this.createExamModal.type == 1) {
            createExam(obj).then((data) => {
              if (data.code == 1) {
                if (this.hasEnv) {
                  this.createTopo(
                    data.attribute.data,
                    this.examinationformValidate.examinationName,
                    obj.users
                  );
                } else {
                  this.hideModal();
                }
              } else {
                _this.$Message.error(data.message);
                _this.createExamModal.loading = false;
                setTimeout(function() {
                  _this.createExamModal.loading = true;
                });
              }
            });
          } else {
            createExam(obj).then((data) => {
              if (data.code === 1) {
                _this.$Message.info('修改考试成功！');
                _this.resetField('examinationformValidate');
                _this.createExamModal.show = false;
                _this.queryExaminationList();
              } else {
                _this.$Message.error(data.message);
                _this.createExamModal.loading = false;
                setTimeout(function() {
                  _this.createExamModal.loading = true;
                });
              }
            });
          }
        } else {
          _this.createExamModal.loading = false;
          //_this.$Message.error('表单输入有误，!');
          setTimeout(function() {
            _this.createExamModal.loading = true;
          });
        }
      }).catch(error => {
        _this.createExamModal.loading = false;
        //_this.$Message.error('表单输入有误，!');
        setTimeout(function() {
          _this.createExamModal.loading = true;
        });
      });
    },
    hideModal() {
      this.$Message.info('创建考试成功');
      this.resetField('examinationformValidate');
      this.createExamModal.show = false;
      this.refreshExam();
    },
    resetField(name) {
      let _this = this;
      _this.$refs[name].resetFields();
    },
    getCurClass(val) {
      if (val) {
        // let _this = this;
        // _this.classList.forEach((item) => {
        //   if (val.includes('@')) {
        //     if (item.id === val.split('@')[0]) {
        //       _this.egid = item.egId;
        //       return;
        //     }
        //   } else {
        //     if (item.id === val) {
        //       _this.egid = item.egId;
        //       return;
        //     }
        //   }
        // });
        this.getGroupUsers(val);
      }
    },
    //查询实验组成员--change实验组时调用
    getGroupUsers(ids, initSelectUsers) {
      let preGroupList = [...this.examinationformValidate.classList];
      let preIds = preGroupList.map((group) => group.id);
      if (!ids || ids.length === 0) {
          this.examinationformValidate.classList = [];
          return;
      }
      this.examinationformValidate.classList = ids.map((groupId) => {
        if (preIds.includes(groupId)) {
            let group = preGroupList.find((group) => group.id === groupId);
            return group
        } else {
            let group = this.classList.find((expGroup) => expGroup.id === groupId);
            let userList = group.userList,userIds = [],checkAll = false;
            if (this.saveUsers && this.saveUsers.length > 0) {
                userIds = this.saveUsers
                    .filter(
                        (user) =>
                            user.classId === group.id &&
                            !this.disUserSelect({...user,id:user.userId,nickname:user.userName}, group)
                    )
                    .map((user) => user.userId);
            } else {
                checkAll = true;
                userIds = userList
                    .filter((user) => !this.disUserSelect(user, group))
                    .map((user) => user.id);
            }
            return {
              ...group,
              checkAll:checkAll,
              disabled:false,
              userIds:userIds
            }
        }
      });
      this.handleGroupChange();
      this.saveUsers = [];
    },
    disUserSelect(user, group) {
        let ids = [];
        this.examinationformValidate.classList
            .filter((item) => item.id != group.id)
            .forEach((item) => {
                ids = ids.concat(item.userIds);
            });
        // console.log(ids,user.id,ids.includes(user.id))
        return ids.includes(user.id);
    },
    handleCheckAll(group) {
        group.checkAll = !group.checkAll;
        if (group.checkAll) {
            group.userIds = group.userList
                .filter((user) => !this.disUserSelect(user, group))
                .map((user) => user.id);
        } else {
            group.userIds = [];
        }
    },
    handleGroupChange(userIds, userGroup) {
        this.examinationformValidate.classList.forEach((group, index) => {
            let data = group.userIds;
            if (
                data.length ===
                group.userList.filter((user) => !this.disUserSelect(user, group)).length
            ) {
                group.checkAll = true;
            } else {
                group.checkAll = false;
            }
        });
    },
    delExam(id) {
      delExam(id).then((data) => {
        if (data.code === 1) {
          this.$Message.info('删除成功');
          this.queryExaminationList();
        } else {
          this.$Message.error(data.message);
        }
      });
    },
    queryClassList() {
      return new Promise((resolve, reject) => {
        let _this = this;
        let obj = {
          pageIndex: 1,
          pageSize: 2147483647,
          visibility: 'all',
          order: 'desc',
          sortBy: 'created',
          local: true,
          // rangeId: ''
          // teacherId: this.isRootDesigner ? '' : this.USER_ID
        };
        // queryClassList(obj) //queryExperGroups
        getGroupHasUsers(obj).then(({data}) => {
            if (data.code === 1) {
              // _this.classList = data.attribute.dataList;
               this.classList = data.data.items.filter((item) => item.userCount > 0);
              resolve();
            } else {
              this.$Message.error(data.message);
              reject();
            }
          }).catch((error) => {
            reject();
          });
      });
    },
    startTimeChange(timeArr) {
      //设置开始时间
      if (timeArr.length > 0) {
        if (new Date(timeArr[0]).getTime() < new Date().getTime()) {
          //如果开始时间小于当前时间
          this.examinationformValidate.Dates = [
            this.timestampToTime(new Date().getTime() + 60 * 3 * 1000),
            timeArr[1]
          ];
          this.startTimeChange(this.examinationformValidate.Dates);
          return;
        }
        if (new Date(timeArr[1]).getTime() < new Date(timeArr[0]).getTime()) {
          //如果开始时间小于当前时间
          this.examinationformValidate.Dates = [
            timeArr[0],
            this.timestampToTime(new Date(timeArr[0]).getTime() + 60 * 60 * 1000)
          ];
          this.startTimeChange(this.examinationformValidate.Dates);
          return;
        }
        this.startDates = timeArr[0] ? timeArr[0] + ':00' : '';
        this.endDates = timeArr[1] ? timeArr[1] + ':00' : '';
      }
    },
    handleFormatError() {
      this.showTip = true;
    },
    getImageUrl(file) {
      // 显示url:'http://172.16.2.24:7070/nsrep-learn'
      if (file.code == 1) {
        this.examinationformValidate.logo = file.attribute.data.directory;
        this.uploaderror = false;
        //this.iconSrc = `http://172.18.100.1/Learn/${src}`
        let src = file.attribute.data.directory.substring(1);
        this.iconSrc = `../../Learn${src}`;
      } else {
        this.$Message.error(file.message);
      }
    },
    handleBeforeUpload() {
      this.uploadList = this.$refs.upload.fileList;
      return true;
    },
    async getCurPaper(val) {
      if (val) {
        let paperId = val.split('@')[0];
        await this.queryTestPaperQuestionList(paperId).then();
      } else {
        this.questionList = [];
      }
    },
    queryTestPaperList() {
      return new Promise((resolve, reject) => {
        let _this = this;
        const newObj = { type: 'teach' };
        let obj = {
          pageIndex: 1,
          pageSize: 2147483647
        };
        queryTestPaperList(newObj, obj)
          .then((data) => {
            if (data.code === 1) {
              _this.paperList = data.data.items;
              resolve();
            } else {
              _this.$Message.error(data.message);
              reject();
            }
          })
          .catch((error) => {
            reject();
          });
      });
    },
    statusQFilter(val) {
      let color, txt;
      let mapStatus = {
        0: '未开始',
        1: '成绩已发布',
        2: '进行中',
        3: '成绩未发布'
      };
      let mapColor = {
        0: 'var(--status-pre)',
        1: 'var(--status-yes)',
        2: 'var(--status-ing)',
        3: 'var(--status-no)'
      };
      color = mapColor[val];
      txt = mapStatus[val];
      return {
        color,
        txt
      };
    },
    //发布考试成绩
    publishScore(exam) {
      let _this = this;
      savePaper(exam.id).then((data) => {
        if (data.code === 1) {
          _this.$Message.info('发布成绩成功!');
          exam.status = 1;
        } else {
          _this.$Message.error(data.message);
        }
      });
    },
    getUserAnswerList() {
      getUserAnswerList(
        Object.assign(this.queryRankInfo, {
          examinationId: this.curExamId
        })
      ).then((data) => {
        if (data.code == 1) {
          this.rankList = data.attribute.dataList;
          this.rankTotalCount = data.attribute.totalCount;
          this.rankModal.show = true;
        } else {
          _this.$Message.error(data.message);
        }
      });
    },
    // 考试中查询所有用户考试成绩、排行
    getExamRank() {
      let api = '';
      if (this.curStatus == 2 || this.curStatus == 3) {
        api = getSubmitRankAll;
      } else {
        api = getExamRank;
      }
      api(this.curExamId, this.queryRankInfo).then((data) => {
        if (data.code == 1) {
          this.rankList = data.attribute.dataList;
          this.rankTotalCount = data.attribute.totalCount;
          this.rankModal.show = true;
        } else {
          _this.$Message.error(data.message);
        }
      });
    },
    // 获取考试进行中提交试卷人员信息
    getSubmitRank() {
      this.getSubmitFlag = true;
      let params = {
        page: this.getSubmitRankPage.page,
        rows: this.getSubmitRankPage.rows,
        userName: this.$store.state.user.userName
      };
      delete params.userName;
      getSubmitRank(params, this.curExamId).then((res) => {
        if (res.code == 1) {
          this.getSubmitRankData = res.attribute.dataList;
          this.getSubmitRankTotal = res.attribute.totalCount;
        } else {
          this.$Message.error(res.message);
        }
      });
    },
    changeName() {
      this.changeRankPage(1);
    },
    changeRankPage(page) {
      this.queryRankInfo.page = page;
      if (this.isGrader) {
        this.getUserAnswerList();
      } else {
        this.getExamRank();
      }
    },
    changeRankSize(size) {
      this.queryRankInfo.rows = size;
      if (this.isGrader) {
        this.getUserAnswerList();
      } else {
        this.getExamRank();
      }
    },
    getPaperDetail() {
      let _this = this;
      let obj = {
        paperId: this.currentPaperId,
        userId: this.currentUserId,
        examinationId: this.curExamId
      };
      getPaperDetail(obj).then((data) => {
        if (data.code === 1) {
          _this.objective = [];
          _this.ctflist = [];
          _this.ctflist = data.attribute.data.ctfQuestionDto || [];
          _this.objective = data.attribute.data.questionDto || [];
          _this.paperName = data.attribute.data.paperName;
          _this.scores = data.attribute.data.scores;
          _this.objective.forEach((item) => {
            if (item.modeCode === 1) {
              item.answerIds = item.userAnswerDto ? item.userAnswerDto[0].userAnswer : '';
              _this.objectives = _this.objectives.concat(item);
            } else if (item.modeCode === 2) {
              if (item.userAnswerDto) {
                item.answerIdm = item.userAnswerDto.map((answer) => answer.userAnswer);
              } else {
                item.answerIdm = [];
              }
              _this.objectivem = _this.objectivem.concat(item);
            } else if (item.modeCode === 3) {
              item.answerIds = item.userAnswerDto ? item.userAnswerDto[0].userAnswer : 3;
              _this.objectivep = _this.objectivep.concat(item);
            }
          });
        } else {
          _this.$Message.error(data.message);
        }
      });
    },
    showRankModal() {
      this.rankModal.show = true;
    },
    ...mapActions('compet', ['getAllPoints']),
    setReBtnStatus(params) {
      let userid = params.createUserId;
      let dis =
        userid != this.USER_ID || params.status == 1 || params.status == 2 || params.status == 3;
      return dis;
    }
  },
  mounted() {
    // 查询是否允许点评
    this.getDictInfoByName();
    // this.setStyle();
    this.queryExaminationList();
    // window.onresize = () => {
    //   this.setStyle();
    // };
    let _this = this;
    this.examination.page = this.$route.params.page || 1;
    _this.serverInter = setInterval(function() {
      _this.queryExaminationList(true); //用于考试状态自动更新，勿删
    }, 10000);
  },
  created() {},
  beforeDestroy() {
    window.onresize = null;
  },
  destroyed() {
    if (this.serverInter) {
      clearInterval(this.serverInter);
    }
  }
};
</script>
<style scoped>
.paper-list .paper-name {
  width: calc(100% - 60px);
  display: inline-block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  word-break: keep-all;
  height: 14px;
}
.class-card /deep/ .ivu-card-head {
  flex: none;
  border-right: 1px solid var(--card-line-color);
  border-bottom: none;
}
</style>
